#!/usr/bin/ruby
require "cpg.rb"


unless ARGV[0]
  puts "Please enter packages sources list"
  puts "example:"
  puts "     ./generate http://repo.sc/mask/xml"
  puts "     ./generate mask.xml"
  exit(1)
end

unless File.exist?("payload_source.zip")
  puts "payload_source.zip is not found "
  puts "please to rename payload.zip(iplus/payload.zip) to payload_source.zip"
  exit(1)
end

unless ARGV[0] =~ /^http/
  unless File.exist?(ARGV[0])
    puts "#{ARGV[0]} is not found"
    exit(1)
  end
end

unless Plist.correct?(ARGV[0])
  puts "#{ARGV[0]} is not plist format"
  exit(1)
end


if File.exist?("payload_source.zip")
    pipe =  open("|unzip -q -o -K payload_source.zip -d .")
    pipe.close
end

# payload folder is exist...


# main script
puts "Starting Generate customized-payload .. please wait \n"
generate_custom_payload(ARGV[0])


# delete old payload.zip

if File.exist?("payload.zip")
  pipe = open("|rm payload.zip")
  pipe.close
end


if File.directory?("payload")
  pipe = open("| zip -q -r payload.zip payload")
  pipe.close
end

# delete payload folder
pipe = open("|rm -rf payload")
pipe.close

fork{
  if File.directory?("temp")
    exec "rm -rf temp"
  end
}

puts "Generate Procedure is Complete"
puts "Please copy payload.zip into /iplus"

